package com.atguigu.tingshu.user.strategy.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.strategy.PaidRecordStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author: atguigu
 * @create: 2024-08-23 10:32
 */
@Slf4j
@Component("1002")
public class TrackPaidRecordStrategy implements PaidRecordStrategy {

    @Autowired
    private AlbumFeignClient albumFeignClient;

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    /**
     * 处理购买商品类型为声音-发货逻辑
     * @param userPaidRecordVo
     */
    @Override
    public void handlerPaidRecord(UserPaidRecordVo userPaidRecordVo) {
        log.info("[用户服务]处理购买商品类型为声音发货逻辑");
        //1.根据订单编号查询是否处理过声音购买记录
        LambdaQueryWrapper<UserPaidTrack> userPaidTrackLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userPaidTrackLambdaQueryWrapper.eq(UserPaidTrack::getOrderNo, userPaidRecordVo.getOrderNo());
        userPaidTrackLambdaQueryWrapper.select(UserPaidTrack::getId);
        if (userPaidTrackMapper.selectCount(userPaidTrackLambdaQueryWrapper) > 0) {
            return;
        }
        //2.保存声音购买记录
        //2.1 根据声音ID查询声音信息获取所属专辑ID
        List<Long> trackIdList = userPaidRecordVo.getItemIdList();
        if (CollectionUtil.isNotEmpty(trackIdList)) {
            TrackInfo trackInfo = albumFeignClient.getTrackInfo(trackIdList.get(0)).getData();
            Long albumId = trackInfo.getAlbumId();
            for (Long trackId : trackIdList) {
                UserPaidTrack userPaidTrack = new UserPaidTrack();
                userPaidTrack.setAlbumId(albumId);
                userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
                userPaidTrack.setTrackId(trackId);
                userPaidTrack.setUserId(userPaidRecordVo.getUserId());
                userPaidTrackMapper.insert(userPaidTrack);
            }
        }
    }
}
